package com.zis.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zis.auth.service.ISercretInter;
import com.zis.core.ResponseEntity;
import com.zis.sms.CCPRestSmsSDK;
import com.zis.utils.PhoneUtils;
import com.zis.utils.RandomUtil;
import com.zis.utils.SecurityUtil;
import com.zis.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * Create by wangshen 2017/12/21
 */
@Service
public class SercretInterImpl implements ISercretInter {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    //登录有效时间2小时
    private long LOGIN_INVALID_TIME = 2*60*60L;

    //验证码有效时间10分钟
    private long AUTH_CODE_INVALID_TIME = 10*60L;


    /**
     * 生成连接校验码
     * @param clientType
     * @param uiSign
     * @return
     */
    @Override
    public String generater(String clientType, String uiSign) throws Exception {
        if(clientType.equals("") || uiSign.equals("")){
            return ResponseEntity.createErrorJsonResponse("系统异常");
        }
        String sign = RandomUtil.getRandomStr(128);
        String token = StringUtils.filterSpecialChar(SecurityUtil.AESEncode(sign,uiSign));
        JSONObject client = new JSONObject();
        client.put("uiSign",uiSign);
        client.put("clientType",clientType);
        client.put("sign",sign);
        client.put("token",token);
        redisTemplate.opsForValue().set(token, client);
        //设置有效时间
        redisTemplate.expire(token, LOGIN_INVALID_TIME, TimeUnit.SECONDS);
        return ResponseEntity.createNormalJsonResponse(token);
    }

    /**
     * 用户退出后清空用户信息
     * @param token
     * @return
     */
    @Override
    public String clear(String token) throws Exception {
        if(redisTemplate.hasKey(token)){
            redisTemplate.delete(token);
        }
        return ResponseEntity.createNormalJsonResponse("清空连接信息成功");
    }

    /**
     * 获取用户登陆信息
     * @param token
     * @return
     */
    @Override
    public String getClient(String token) throws Exception {
        if(!redisTemplate.hasKey(token)){
            return ResponseEntity.createNULLJsonResponse("用户未登陆或登陆信息失效");
        }
        Long expire = redisTemplate.getExpire(token);
        JSONObject client = (JSONObject) redisTemplate.opsForValue().get(token);
        if(expire < 1000){
            redisTemplate.expire(token, LOGIN_INVALID_TIME, TimeUnit.SECONDS);
        }
        return ResponseEntity.createNormalJsonResponse(client);
    }

    /**
     * 更新用户信息
     * @param client
     * @return
     */
    @Override
    public String updateClientUser(JSONObject client) throws Exception {
        String token = client.getString("token");
        if(!redisTemplate.hasKey(token)){
            return "1";
        }
        redisTemplate.opsForValue().set(token, client);
        //设置有效时间
        redisTemplate.expire(token, LOGIN_INVALID_TIME, TimeUnit.SECONDS);
        return "0";
    }

    /**
     * 生成短信验证码
     * @param telephone
     * @return
     * @throws Exception
     */
    @Override
    public String getSmsCode(String telephone) throws Exception {
        if(telephone==null||telephone.equals("")){
            return ResponseEntity.createErrorJsonResponse("请输入手机号码");
        }
        if(!PhoneUtils.isPhoneLegal(telephone)){
            return ResponseEntity.createErrorJsonResponse("请输入正确的手机号码");
        }
        String smsCode = RandomUtil.getSmsCode();
        CCPRestSmsSDK sms = new CCPRestSmsSDK();
        HashMap<String, Object> result = sms.sendTemplateSMS(telephone,"238835",new String[]{smsCode+"","10"});
        if(result.get("statusCode").equals("000000")){
            redisTemplate.opsForValue().set(telephone, smsCode);
            redisTemplate.expire(telephone, AUTH_CODE_INVALID_TIME, TimeUnit.SECONDS);
            return ResponseEntity.createNormalJsonResponse("验证码获取成功");
        }else {
            return ResponseEntity.createErrorJsonResponse("验证码获取失败");
        }
    }

    /**
     * 验证码校验
     * @param telephone
     * @param authCode
     * @return
     * @throws Exception
     */
    @Override
    public String verifySmsCode(String telephone, String authCode) throws Exception {
        if(!redisTemplate.hasKey(telephone)){
            return "验证码已失效";
        }
        String cacheCode = redisTemplate.opsForValue().get(telephone).toString();
        if(!cacheCode.equals(authCode)){
            return "验证码错误";
        }
        redisTemplate.delete(telephone);//校验通过移除cache
        return "ok";
    }

    public static void main(String[] args) {
        CCPRestSmsSDK sms = new CCPRestSmsSDK();
        HashMap<String, Object> result = sms.sendTemplateSMS("13201862731","229101",new String[]{"9999222","10"});
        System.out.println(JSON.toJSONString(result));
    }
}
